package be.kuleuven.cs.mop.domain.model.impl;


import java.util.Collections;
import java.util.Comparator;
import java.util.List;



public class FocusWorkAlgorithmDeadline extends FocusWorkAlgorithm {
	
	/**
	 * The maximum number of tasks to be returned
	 */
	private final int max;
	
	/**
	 * Represents a deadline-based template method implementation for the "Focus Work" use case
	 */
	public FocusWorkAlgorithmDeadline(final UserImpl user, final int max) {
		super(user);
		if (max < 0)
			throw new IllegalArgumentException("max < 0");
		this.max = max;
	}
	
	/**
	 * A comparator that compares two tasks based on their deadline
	 */
	protected Comparator<TaskImpl> getComparator() {
		return new Comparator<TaskImpl>() {
			@Override
			public int compare(final TaskImpl a, final TaskImpl b) {
				return a.getSchedule().getDeadline().compareTo(
						b.getSchedule().getDeadline());
			}
		};
	}
	
	/**
	 * Sorts the list of tasks based on the comparator above
	 */
	@Override
	protected void sort(final List<TaskImpl> tasks) {
		Collections.sort(tasks, getComparator());
	}
	
	/**
	 * Makes sure only 'max' available tasks are in the list after execution.
	 */
	@Override
	protected void filter(final List<TaskImpl> tasks) {
		for (final TaskImpl task : tasks.toArray(new TaskImpl[tasks.size()]))
			if (!task.isAvailable())
				tasks.remove(task);
		
		for (int n = tasks.size(); n > max; n = tasks.size())
			tasks.remove(n - 1);
	}
	
}